define(function (require, exports, module) {

    require("apps/grid");
    require("apps/easyui");

    function formatDate(date) {
        var year = date.getFullYear();
        var month = addZero(date.getMonth() + 1);
        var day = addZero(date.getDate());
        var hour = addZero(date.getHours());
        var min = addZero(date.getMinutes());
        var sec = addZero(date.getSeconds());
        return year + "-" + month + "-" + day + " " + hour + ":" + min/*+":"+sec*/;
    };

    function addZero(number) {
        return number > 9 ? number + "" : "0" + number;
    }


    exports.init = function (ctx, uuid, config) {
        var pageListComponent = new $.PageListComponent(uuid, {
            view: {
                grid: "grid",
                myToolbar: "nsdb",
                colbar: "attendance_tempate"
            },
            configs: {
                gridUrl: ctx + '/app/api/attendance/approList',
                gridColumns: [
                    {
                        field: 'id',
                        checkbox: true
                    },
                    {
                        field: 'reason.dirValue',
                        title: '考勤事由',
                        width: 90,
                        align: 'center'

                    },
                    {
                        field: 'remark',
                        title: '备注',
                        width: 160,
                        align: 'center'

                    },
                    {
                        field: 'applyUser.userName',
                        title: '人员',
                        width: 90,
                        align: 'center'
                    },
                    {
                        field: 'createUser.userName',
                        title: '填报人',
                        width: 100,
                        align: 'center',
                        formatter: function (value, row, index) {
                            if (row.isReplace == 1) {
                                return value + "(代填)"
                            }
                            return value;
                        }
                    },
                    {
                        field: 'createTime',
                        title: '填报时间',
                        width: 130,
                        align: 'center'
                    },
                    {
                        field: 'beginTime',
                        title: '开始时间',
                        width: 130,
                        align: 'center'
                    },
                    {
                        field: 'endTime',
                        title: '结束时间',
                        width: 130,
                        align: 'center',
                        formatter: function (value, row, index) {
                            if (value == null) {
                                return "暂无";
                            }
                            return value;
                        }
                    },
                    {
                        field: 'hourOrDay',
                        title: '小计',
                        width: 100,
                        align: 'center',
                        formatter: function (value, row, index) {
                            if (value == null) {
                                return "暂无";
                            }
                            return value;
                        }
                    }
                ]
            },
            events: {
                renderColBarBefore: function (type, row) {
                    if (type == "edit") {
                        return row.endTime == null;
                    }
                    return true;
                },
                onClickColBtn: function (context, btn, row) {
                    switch (btn.key) {
                        case "view":
                            whenView(context, btn.href, row.id);
                            break;
                        default :
                            break;
                    }
                },
                onClickToolbarBtn: function (context, btn) {
                    switch (btn.key) {
                        case "search_all":
                            context.searchAll();
                            break;
                        case "search":
                            context.search(btn.href, "考勤登记搜索", "attendance_search");
                            break;
                        case "pass":
                            whenPass(context, btn.href);
                            break;
                        case "refuse":
                            whenRefuse(context, btn.href);
                            break;
                        case "exportAppro":
                            whenDownload(context, btn.href);
                            break;
                        default :
                            break;
                    }
                }
            }
        });

        var contextWindow = new $.PageWindow();

        function _appro(context, href, approvalType) {
            var firstSelected = context.grid.datagrid('getChecked');
            //debugger;
            if (firstSelected.length == 0) {
                $.messager.alert('信息', "请先选择一行!", 'info');
                context.grid.datagrid('clearSelections');
                return;
            }
            var postData = {approvalType: approvalType}
            postData.ids = firstSelected.map(function (item) {
                return item.id;
            }).join(",");
            var des = approvalType === "1" ? "通过" : "拒绝";
            $.messager.confirm("审批确认", "是否将已选择的登记记录审批" + des + "？", function (args) {
                if (args) {
                    $("body").wait("start", "保存中,请稍候.");
                    $.post(href
                        + "?random=" + Math.random(), postData,
                        function (json) {
                            $("body").wait("end");
                            if ($.utils.isError(json)) {
                                $.messager.alert('信息',
                                    json.msg, 'info');
                            } else {
                                $.messager.alert('信息',
                                    '审批成功', 'info');
                                context.grid.datagrid("reload");
                            }
                        }, "json");
                }
            })
        }

        function whenPass(context, href) {
            _appro(context, href, "1");
        }

        function whenRefuse(context, href) {
            _appro(context, href, "0");
        }

        function whenDownload(context, href){
            $("body").append("<iframe src='" + href + "' style='display:none'></iframe>");
        }

        function whenView(context, href, id) {
            contextWindow.create({
                href: href + "?id=" + id,
                title: "考勤登记详情",
                width: 500
            });
            contextWindow.open();
        }

        var page = new $.PageDomFactory(uuid, true);
        page.getJqDom("form-attendance-add-info").find(".easyui-validatebox").validatebox();
        page.getJqDom("reason").combobox({
            loadFilter: function (data) {
                return data.content;
            },
            url: ctx + "/app/api/directory/list?dirGroup=DIRECTORY_REASON_TYPE",
            valueField: 'id',
            textField: 'dirValue',
            onSelect: function (record) {
                if (page.getJqDom("isReplace").is(":checked")) {
                    var userId = page.getJqDom("applyUser2").combogrid("getValue");
                    if (userId != null && userId != "") {
                        prompt(record.id, userId);
                    }
                } else {
                    prompt(record.id, config.loginUserId);
                }

//                if(record.dirValue == "加班"){
//                    page.getJqDom("pCodeItem").show();
//                    page.getJqDom("projectCode").validatebox("enableValidation");
//                }else{
//                    page.getJqDom("pCodeItem").hide();
//                    page.getJqDom("projectCode").val("");
//                    page.getJqDom("projectCode").validatebox("disableValidation");
//                }

                if (record.dirValue == "加班" || record.dirValue == "公干" || record.dirValue == "零星事假") {
                    page.getJqDom("beginTime1").datebox("disable");
                    page.getJqDom("hourBegin").show();
                    page.getJqDom("dayBegin").hide();
                } else {
                    page.getJqDom("beginTime1").datebox("enable");
                    page.getJqDom("hourBegin").hide();
                    page.getJqDom("dayBegin").show();
                }
            }
        });

        page.getJqDom("beginTime").datetimebox({
            showSeconds: false
        });
        page.getJqDom("beginTime").datetimebox('setValue', formatDate(new Date()));

        page.getJqDom("beginTime1").datebox();
        page.getJqDom("apm").combobox({
            editable: false
        });

        page.getJqDom("applyUser1").combobox({
            url: ctx + '/app/api/sysMember/list',
            valueField: 'id',
            textField: 'userName',
            onLoadSuccess: function () {
                page.getJqDom("applyUser1").combobox("setValue", config.loginUserId);
                page.getJqDom("applyUser1").combobox("disable");
            }
        });

        page.getJqDom("applyUser2").userSelect({
            url: ctx + "/app/api/sysMember/allUserButMe",
            organizationUrl: ctx + "/app/api/organization/findAll",
            onSelect: function () {
                var reasonId = page.getJqDom("reason").combobox("getValue");
                if (reasonId != null && reasonId != "") {
                    prompt(reasonId, page.getJqDom("applyUser2").combogrid("getValue"));
                }
            }
        });

        firstInto();

        function firstInto() {
            if (config.userId == "" || config.userId == config.loginUserId) {
                noCheck();
            } else {
                yesCheck();
                page.getJqDom("applyUser2").combogrid({
                    value: config.userId,
                    store: [{
                        id: config.userId,
                        userName: config.userName
                    }]
                });
            }
        }

        function prompt(reasonId, userId) {
            $.post(
                ctx + "/app/api/attendance/prompt?random=" + Math.random(),
                $.utils.buildJson({reasonId: reasonId, userId: userId}),
                function (json) {
                    if (json.msg != undefined) {
                        page.getJqDom("prompt").html(json.msg);
                    } else {
                        page.getJqDom("prompt").html("");
                    }
                },
                "json"
            );
        }

        page.getJqDom("isReplace").click(function () {
            if ($(this).is(":checked")) {
                yesCheck();
            } else {
                noCheck();
            }
        });

        function noCheck() {
            page.getJqDom("isReplace").attr("checked", false);
            page.getJqDom("loginUserId").attr("disabled", false);
            page.getJqDom("applyUser2").combogrid("setValue", config.loginUserId);
            page.getJqDom("applyUser2").combogrid("disable");
            page.getJqDom("select1").show();
            page.getJqDom("select2").hide();
        }

        function yesCheck() {
            page.getJqDom("isReplace").attr("checked", true);
            page.getJqDom("loginUserId").attr("disabled", true);
            page.getJqDom("applyUser2").combogrid("clear");
            page.getJqDom("applyUser2").combogrid("enable");
            page.getJqDom("form-attendance-add-info").form('validate');
            page.getJqDom("select1").hide();
            page.getJqDom("select2").show();
        }

        page.getJqDom("next").linkbutton({
            onClick: function () {
                var postForm = page.getJqDom("form-attendance-add-info");
                if (!postForm.form('validate')) {
                    return false;
                }
                var postData = postForm.serializeJson();
                $("body").wait("start", "保存中,请稍候.");
                $.post(postForm.attr("action")
                    + "?random=" + Math.random(), $.utils.buildJson(postData),
                    function (json) {
                        $("body").wait("end");
                        if ($.utils.isError(json)) {
                            $.messager.alert('信息',
                                json.msg, 'info');
                        } else {
                            $.messager.alert('信息',
                                '保存成功', 'info');
//                            postForm.form('reset');
//                            window.location.reload();
                            page.getJqDom("grid").datagrid("reload");
                            page.getJqDom("reason").combobox("clear");
                            page.getJqDom("remark").val("");
                            page.getJqDom("prompt").html("");
//                            page.getJqDom("pCodeItem").hide();
//                            page.getJqDom("projectCode").val("");
//                            page.getJqDom("beginTime").datetimebox("clear");
                            page.getJqDom("beginTime").datetimebox('setValue', formatDate(new Date()));
                            page.getJqDom("beginTime1").datebox('setValue', formatDate(new Date()));
                            page.getJqDom("hourBegin").show();
                            page.getJqDom("dayBegin").hide();
                            page.getJqDom("form-attendance-add-info").form('validate');
//                            firstInto();
                            noCheck();
                        }
                    }, "json");
            }
        });
    };

    exports.add = function (ctx, uuid, config) {
        var page = new $.PageDomFactory(uuid, true);

        page.getJqDom("reason").combobox({
            loadFilter: function (data) {
                return data.content;
            },
            url: ctx + "/app/api/directory/list?dirGroup=DIRECTORY_REASON_TYPE",
            valueField: 'id',
            textField: 'dirValue',
            onSelect: function (record) {
                if (page.getJqDom("isReplace").is(":checked")) {
                    var userId = page.getJqDom("applyUser2").combogrid("getValue");
                    if (userId != null && userId != "") {
                        prompt(record.id, userId);
                    }
                } else {
                    prompt(record.id, config.loginUserId);
                }

//                if(record.dirValue == "加班"){
//                    page.getJqDom("pCodeItem").show();
//                    page.getJqDom("projectCode").validatebox("enableValidation");
//                }else{
//                    page.getJqDom("pCodeItem").hide();
//                    page.getJqDom("projectCode").val("");
//                    page.getJqDom("projectCode").validatebox("disableValidation");
//                }

                if (record.dirValue == "加班" || record.dirValue == "公干" || record.dirValue == "零星事假") {
                    page.getJqDom("beginTime1").datebox("disable");
                    page.getJqDom("hourBegin").show();
                    page.getJqDom("dayBegin").hide();
                } else {
                    page.getJqDom("beginTime1").datebox("enable");
                    page.getJqDom("hourBegin").hide();
                    page.getJqDom("dayBegin").show();
                }
            }
        });

        page.getJqDom("beginTime").datetimebox({
            showSeconds: false
        });
        page.getJqDom("beginTime").datetimebox('setValue', formatDate(new Date()));

        page.getJqDom("beginTime1").datebox();
        page.getJqDom("apm").combobox({
            editable: false
        });

        page.getJqDom("applyUser1").combobox({
            url: ctx + '/app/api/sysMember/list',
            valueField: 'id',
            textField: 'userName',
            onLoadSuccess: function () {
                page.getJqDom("applyUser1").combobox("setValue", config.loginUserId);
                page.getJqDom("applyUser1").combobox("disable");
            }
        });

        page.getJqDom("applyUser2").userSelect({
            url: ctx + "/app/api/sysMember/allUserButMe",
            organizationUrl: ctx + "/app/api/organization/findAll",
            onSelect: function () {
                var reasonId = page.getJqDom("reason").combobox("getValue");
                if (reasonId != null && reasonId != "") {
                    prompt(reasonId, page.getJqDom("applyUser2").combogrid("getValue"));
                }
            }
        });

        noCheck();

        page.getJqDom("isReplace").click(function () {
            if ($(this).is(":checked")) {
                yesCheck();
            } else {
                noCheck();
            }
        });

        function noCheck() {
            page.getJqDom("isReplace").attr("checked", false);
            page.getJqDom("loginUserId").attr("disabled", false);
            page.getJqDom("applyUser2").combogrid("setValue", config.loginUserId);
            page.getJqDom("applyUser2").combogrid("disable");
            page.getJqDom("select1").show();
            page.getJqDom("select2").hide();
        }

        function yesCheck() {
            page.getJqDom("isReplace").attr("checked", true);
            page.getJqDom("loginUserId").attr("disabled", true);
            page.getJqDom("applyUser2").combogrid("clear");
            page.getJqDom("applyUser2").combogrid("enable");
            page.getJqDom("form-attendance-add-info").form('validate');
            page.getJqDom("select1").hide();
            page.getJqDom("select2").show();
        }

        function prompt(reasonId, userId) {
            $.post(
                ctx + "/app/api/attendance/prompt?random=" + Math.random(),
                $.utils.buildJson({reasonId: reasonId, userId: userId}),
                function (json) {
                    if (json.msg != undefined) {
                        page.getJqDom("prompt").html(json.msg);
                    } else {
                        page.getJqDom("prompt").html("");
                    }
                },
                "json"
            );
        }

        window.attendance_add_save = function (win) {
            var postForm = page.getJqDom("form-attendance-add-info");
            if (!postForm.form('validate')) {
                return false;
            }
            var postData = postForm.serializeJson();
            win.wait("start", "保存中,请稍候.");
            $.post(postForm.attr("action")
                + "?random=" + Math.random(), $.utils.buildJson(postData),
                function (json) {
                    win.wait("end");
                    if ($.utils.isError(json)) {
                        $.messager.alert('信息',
                            json.msg, 'info');
                        win.callback(false);
                    } else {
                        $.messager.alert('信息',
                            '保存成功', 'info');
                        win.callback(true);
                        win.close();
                    }
                }, "json");
        }
    };

    exports.update = function (ctx, uuid) {
        var page = new $.PageDomFactory(uuid, true);
        page.getJqDom("form-attendance-update-info").find(".easyui-validatebox").validatebox();

        page.getJqDom("beginTime").datetimebox({
            showSeconds: false
        });

        page.getJqDom("endTime").datetimebox({
            showSeconds: false
        });
        page.getJqDom("endTime").datetimebox('setValue', formatDate(new Date()));

        window.attendance_edit_save = function (win) {
            var postForm = page.getJqDom("form-attendance-update-info");
            if (!postForm.form('validate')) {
                return false;
            }
            var postData = postForm.serializeJson();
            win.wait("start", "保存中,请稍候.");
            $.post(postForm.attr("action")
                + "?random=" + Math.random(), $.utils.buildJson(postData),
                function (json) {
                    win.wait("end");
                    if ($.isPlainObject(json) && json.error) {
                        $.messager.alert('信息',
                            json.msg, 'info');
                        win.callback(false);
                    } else {
                        $.messager.alert('信息',
                            '保存成功', 'info');
                        win.callback(true);
                        win.close();
                    }
                }, "json");
        }
    };

    exports.search = function (ctx, uuid) {
        var page = new $.PageDomFactory(uuid, true);

        page.getJqDom("reason").combobox({
            loadFilter: function (data) {
                return data.content;
            },
            url: ctx + "/app/api/directory/list?dirGroup=DIRECTORY_REASON_TYPE",
            valueField: 'id',
            textField: 'dirValue'
        });

        page.getJqDom("applyUser").userSelect({
            url: ctx + "/app/api/sysMember/allUsers",
            organizationUrl: ctx + "/app/api/organization/findAll"
        });

        window.attendance_search = function (win) {
            win.wait("start", "搜索中，请稍候！");
            var form = page.getJqDom("form-attendance-search-info");
            var postData = form.serializeJson();
            win.callback(postData);
            win.close();
        }
    };

//    exports.addTwo = function (ctx, uuid, config) {
//        var page = new $.PageDomFactory(uuid, true);
//
//        function noCheck() {
//            page.getJqDom("isReplace").attr("checked", false);
//            page.getJqDom("applyUser").combogrid({
//                value: config.loginUserId,
//                store: [{
//                    id: config.loginUserId,
//                    userName: config.loginUserName
//                }]
//            });
//            page.getJqDom("applyUser").combogrid("disable");
//            page.getJqDom("loginUserId").attr("disabled", false);
//        }
//
//        function yesCheck() {
//            page.getJqDom("isReplace").attr("checked", true);
//            page.getJqDom("loginUserId").attr("disabled", true);
//            page.getJqDom("applyUser").combogrid("clear");
//            page.getJqDom("applyUser").combogrid("enable");
//            page.getJqDom("form-attendance-add-info").form('validate');
//        }
//    };


});